/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.geminisystems.service;

import com.geminisystems.entity.Product;
import com.geminisystems.exception.EntityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Dmitry
 */
public class ProductServiceImpl implements ProductService {
    
    private static Map<Long, Product> entities = new HashMap<Long, Product>();
    private static long increment = 0;

    public synchronized Long saveProduct(Product product) throws EntityException {
        System.out.println(product.getGroup());
        if(product == null) throw new EntityException("Product shouldn't be null");
        if(product.getId() == null) {
            product.setId(++increment);
        } 
        entities.put(product.getId(), product);
        return product.getId();
    }

    public synchronized void deleteProduct(Product product) throws EntityException {
        if(product == null || product.getId() == null) throw new EntityException("Product shouldn't be null");
        entities.remove(product.getId());
    }

    public synchronized Product getProductById(Long id) {
        return cloneProduct(entities.get(id));
    }

    public synchronized List<Product> findProductsByName(String str) {
        List<Product> result = new ArrayList<Product>();
        for(Product product : entities.values()) {
            if(product.getName().contains(str)) {
                result.add(cloneProduct(product));
            }
        }
        return result;
    }

    public synchronized List<Product> getProducts() {
        List<Product> result = new ArrayList<Product>();
        for(Product product : entities.values()) {
            result.add(cloneProduct(product));
        }
        return result;
    }
    
    private synchronized Product cloneProduct(Product product) {
        if(product == null) return null;
        Product result = new Product();
        result.setId(product.getId());
        result.setName(product.getName());
        result.setDescription(product.getDescription());
        result.setLastmodified(product.getLastmodified());
        result.setPrice(product.getPrice());
        result.setGroup(product.getGroup());
        return result;
    }
    
//    public synchronized void insertNewData() {
//        Product product = new Product();
//    }
    
}
